from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

from apps.verifications.libs.captcha.captcha import captcha
from apps.verifications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code
import random
# Create your views here.
# module 'apps.verifications.libs.captcha.captcha' has no attribute 'generate_captcha'
import logging
logger = logging.getLogger('django')


class ImageCodeView(View):
    """图形验证码
    GET http://www.meiduo.site:8000/image_codes/550e8400-e29b-41d4-a716-446655440000/
    """
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection(alias='verify_code')

        redis_conn.setex('img%s' % uuid, 300, text)

        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):

    def get(self, request, mobile):
        # 1、链接验证码redis数据库
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code':400,
                                      'errmsg':'发送短信验证码过于频繁，请稍后再试'})

        # 2、接收前端用户输入的图形验证码，接受前端生成的uuid
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 3、校验前端传来的参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少必传参数'})

        # 4. 提取图形验证码
        image_code_server = redis_conn.get('img%s' % uuid)
        print(image_code_server)
        if image_code_server is None:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '图形验证码过期'})

        # 5、防止用户在图像验证码的有效期间恶意频繁操作，取出图形验证码后立即删除redis数据库中的记录
        redis_conn.delete('img%s' % uuid)

        # 6、判断用户输入图形验证码是否正确
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '图形验证码有误'})
        # 7. 生成短信验证码：生成3位数验证码
        sms_code = '%03d' % random.randint(0, 999)
        logger.info(sms_code)

        # 8. 保存短信验证码
        # 短信验证码有效期，单位：300秒
        # 将多条对redis数据库操作的语句封装到pipeline中，提高数据库的执行效率
        # redis_conn.setex('sms%s' % mobile, 300, sms_code)
        # 避免用户频繁获取验证码
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl = redis_conn.pipeline()
        pl.setex('sms%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()

        # 9. 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'code': 0,
                                  'errmsg': '发送短信成功'})